package freemarker;

import freemarker.apiConfig.ApiConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import util.FileCreator;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: 张德长 dechang.zhang@ucarinc.com
 * @date: 15:09:45 2018/11/9
 * @version:2.0
 */
public class StartWork {
    private static final String FREEMARKER_PATH = "src/main/java/freemarker";
    private static final String TEMPLATE_PATH = FREEMARKER_PATH + "/module";
    private static final String OUT_PATH = FREEMARKER_PATH + "/output";

    public static void main(String[] args) {
        /*****配置项目根路径***/
        ApiConfig.classPath = "test";
        List<ApiConfig> list = new ArrayList<ApiConfig>();
        int configSize = 4;
        for (int i = 0; i < configSize; i++) {
            //配置项目信息
            ApiConfig api = new ApiConfig("com.test.test", "TEST_TEST", "Test", "测试", "/action/test");
            list.add(api);
        }
        for (int i = 0; i < list.size(); i++) {
            ApiConfig api = list.get(i);
            createJavaFile(api, "serviceComs", "ServiceCom");
            createJavaFile(api, "results", "Result");
            createJavaFile(api, "params", "Param");
            createJavaFile(api, "adapters", "Adapter");

        }
    }

    public static void createJavaFile(ApiConfig api, String packageInfo, String fileName) {
        Configuration configuration = new Configuration();
        Writer out = null;
        try {
            // step2 获取模版路径
            configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
            // step3 创建数据模型
            Map<String, Object> dataMap = api.setModuleConfig();
            // step4 加载模版文件
            Template template = configuration.getTemplate(fileName + ".ftl");
            // step5 生成数据
            String path = OUT_PATH + "\\" + packageInfo + "\\" + api.SERVER_NAME + fileName + ".java";
            FileCreator.checkExist(path);
            File docFile = new File(path);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            // step6 输出文件
            template.process(dataMap, out);
            System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^自动生成 成功 !");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

}
